package com.java.softproblem.exer4;

/**
 * @author luzhikun
 * @date &{DATE}-23:36
 */

/**
 * 使用同步方法解决实现Runnable接口中的线程安全问题
 */
public class Sysctest2 {
    public static void main(String[] args) {
        MyThread_2 myThread = new MyThread_2();
        Thread thread = new Thread(myThread);
        thread.setName("线程一");
        Thread thread1 = new Thread(myThread);
        thread1.setName("线程二");
        Thread thread2 = new Thread(myThread);
        thread2.setName("线程三");
        thread.start();
        thread1.start();
        thread2.start();
    }
}

class MyThread_2 implements Runnable {
    private int ticket = 100;

    @Override
    public void run() {
        while (true) {
            show();
        }
    }

    public synchronized void show() {        //同步监视器默认：this
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "恭喜你买到了票" + ticket);
            ticket--;
        }

    }
}
